import { Injectable } from '@nestjs/common';
import { InjectEntityManager } from "@nestjs/typeorm";
import { EntityManager } from 'typeorm';
import { Booking } from "src/booking/entities/booking.entity";
import { User } from "src/user/entities/user.entity";
import { MeetingRoom } from "src/meeting-room/entities/meeting-room.entity";

@Injectable()
export class StatisticService {

    @InjectEntityManager()
    private entityManager: EntityManager;

    async userBookingCount(startTime: string, endTime: string) {
        // 统计相关的 sql 比较复杂，我们使用 queryBuilder 的 api，这种写法和写 sql 的体验差不多。
        const res = await this.entityManager
            .createQueryBuilder(Booking, 'b')
            .select('u.id', '用户id')
            .addSelect('u.username', '用户名')
            .leftJoin(User, 'u', 'b.userId = u.id')
            .addSelect('count(1)', '预定次数')
            .where('b.startTime between :time1 and :time2', {
                time1: startTime,
                time2: endTime,
            })
            .addGroupBy('b.user')
            .getRawOne();

        return res;
    }

    async meetingRoomUsedCount(startTime: string, endTime: string) {
        const res = await this.entityManager
            .createQueryBuilder(Booking, 'b')
            .select('m.id', 'meetingRoomId')
            .addSelect('m.name', 'meetingRoomName')
            .leftJoin(MeetingRoom, 'm', 'b.roomId = m.id')
            .addSelect("count(1)", 'usedCount')
            .where('b.startTime between :time1 and :time2', {
                time1: startTime,
                time2: endTime
            })
            .addGroupBy('b.roomId')
            .getRawOne();

        return res;
    }
}
